<template>
  <div class="app-container">
    <!-- 查询区域 -->
    <el-card class="search-card" v-show="showSearch">
      <el-form :model="queryParams" :inline="true">
        <el-form-item label="方案名称">
          <el-input v-model="queryParams.schemeName" placeholder="请输入方案名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="系统名称">
          <el-input v-model="queryParams.systemName" placeholder="请输入系统名称" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="是否默认">
          <el-select v-model="queryParams.isDefault" placeholder="请选择是否默认" clearable style="width: 200px">
            <el-option label="全部" value="" />
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker v-model="timeRange" type="daterange" range-separator="至" start-placeholder="开始日期"
            end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 300px" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据表格区域 -->
    <el-card class="mt-2">
      <!-- 操作按钮和右侧工具栏 -->
      <el-row :gutter="20">

        <el-col :span="1.5">
          <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" plain icon="Download" @click="handleExport">导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="fetchMenuSchemeList"
          :columns="columns"></right-toolbar>
      </el-row>

      <!-- 数据表格 -->
      <el-table :data="schemeList" v-loading="loading" @selection-change="handleSelectionChange" class="mt-2">
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column type="index" label="序号" width="55" align="center" />

        <el-table-column prop="schemeName" label="方案名称" align="center" v-if="columns[0].visible" />
        <el-table-column prop="schemeDesc" label="方案描述" align="center" v-if="columns[1].visible" />
        <el-table-column prop="systemName" label="系统名称" align="center" v-if="columns[2].visible" />
        <el-table-column label="是否默认" align="center" width="120" v-if="columns[3].visible">
          <template #default="{ row }">
            <el-tag :type="row.isDefault === 1 ? 'success' : 'info'">
              {{ row.isDefault === 1 ? '是' : '否' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="用户类型" align="center" width="120" v-if="columns[4].visible">
          <template #default="{ row }">
            <el-tag :type="getUserTypeTagType(row.userType)">
              {{ getUserTypeLabel(row.userType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="menuCollection" label="菜单集合" align="center" v-if="columns[5].visible">
          <template #default="{ row }">
            <el-button type="text" @click="handleViewMenus(row)">查看菜单</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" align="center" width="180" v-if="columns[6].visible" />
        <el-table-column prop="creator" label="创建人" align="center" width="120" v-if="columns[7].visible" />
        <el-table-column label="操作" width="300" align="center" fixed="right" v-if="columns[8].visible">
          <template #default="{ row }">
            <el-button type="text" icon="More" @click="handleDetail(row)">查看详情</el-button>
            <el-button type="text" icon="Edit" @click="handleEdit(row)">编辑</el-button>
            <el-button type="text" icon="Delete" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination class="mt-2" background layout="total, sizes, prev, pager, next, jumper" :total="total"
        v-model:page-size="queryParams.pageSize" v-model:current-page="queryParams.pageNum"
        @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="800px" :close-on-click-modal="false"
      @close="handleCloseDialog">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="方案名称" prop="schemeName">
          <el-input v-model="form.schemeName" placeholder="请输入方案名称" />
        </el-form-item>
        <el-form-item label="方案描述" prop="schemeDesc">
          <el-input v-model="form.schemeDesc" type="textarea" :rows="3" placeholder="请输入方案描述" />
        </el-form-item>
        <el-form-item label="系统名称" prop="systemName">
          <el-input v-model="form.systemName" placeholder="请输入系统名称" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="form.userType" placeholder="请选择用户类型" style="width: 100%">
            <el-option label="管理员" value="admin" />
            <el-option label="普通用户" value="user" />
            <el-option label="访客" value="guest" />
          </el-select>
        </el-form-item>
        <el-form-item label="是否默认" prop="isDefault">
          <el-select v-model="form.isDefault" placeholder="请选择是否默认" style="width: 100%">
            <el-option label="是" :value="1" />
            <el-option label="否" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item label="菜单集合" prop="menuCollection">
          <el-input v-model="form.menuCollection" type="textarea" :rows="6" placeholder="请输入菜单集合JSON格式，如 [1,2,3]" />
          <div class="form-tip">格式：菜单ID数组，如 [1,2,3,4,5]</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </template>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog v-model="detailDialog.visible" :title="`菜单方案详情 - ${detailData.schemeName}`" width="800px"
      :close-on-click-modal="false">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="方案名称">{{ detailData.schemeName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="方案描述">{{ detailData.schemeDesc || '-' }}</el-descriptions-item>
        <el-descriptions-item label="系统名称">{{ detailData.systemName || '-' }}</el-descriptions-item>
        <el-descriptions-item label="是否默认">
          <el-tag :type="detailData.isDefault === 1 ? 'success' : 'info'">
            {{ detailData.isDefault === 1 ? '是' : '否' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="用户类型">
          <el-tag :type="getUserTypeTagType(detailData.userType)">
            {{ getUserTypeLabel(detailData.userType) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="菜单集合" :span="2">
          <el-input v-model="detailData.menuCollection" type="textarea" :rows="4" readonly />
        </el-descriptions-item>
        <el-descriptions-item label="创建人">{{ detailData.creator || '-' }}</el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ detailData.createTime || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新人">{{ detailData.updater || '-' }}</el-descriptions-item>
        <el-descriptions-item label="更新时间">{{ detailData.updateTime || '-' }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="detailDialog.visible = false">关闭</el-button>
        <el-button type="primary" @click="handleEdit(detailData)">编辑</el-button>
      </template>
    </el-dialog>

    <!-- 查看菜单对话框 -->
    <el-dialog v-model="menuDialog.visible" :title="`菜单集合 - ${menuDialog.schemeName}`" width="600px"
      :close-on-click-modal="false">
      <el-table :data="menuList" border>
        <el-table-column prop="menuId" label="菜单ID" align="center" width="100" />
        <el-table-column prop="menuName" label="菜单名称" align="center" />
        <el-table-column prop="menuPath" label="菜单路径" align="center" />
      </el-table>
      <template #footer>
        <el-button @click="menuDialog.visible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import RightToolbar from '@/components/RightToolbar'
import {
  listMenuSchemes,
  exportMenuSchemes,
  getMenuSchemeDetail,
  addMenuScheme,
  updateMenuScheme,
  deleteMenuSchemes,
  getMenuCollectionList
} from '@/api/appCenter/menu_scheme'


const handleCloseDialog = () => {
  resetForm()

}

const formRef = ref(null);
// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  schemeName: '',
  systemName: '',
  isDefault: '',
  startTime: '',
  endTime: ''
})

const timeRange = ref([])
const schemeList = ref([])
const total = ref(0)
const loading = ref(false)
const selectedRows = ref([])
const showSearch = ref(true)

// 对话框控制
const dialog = reactive({
  visible: false,
  title: '新增菜单方案',
  isEdit: false
})

// 表单数据
const form = ref({
  schemeId: undefined,
  schemeName: '',
  schemeDesc: '',
  systemName: '',
  menuCollection: '',
  userType: '',
  isDefault: 0
})

// 详情对话框控制
const detailDialog = reactive({
  visible: false
})

// 详情数据
const detailData = ref({})

// 菜单对话框控制
const menuDialog = reactive({
  visible: false,
  schemeName: ''
})

// 菜单列表数据
const menuList = ref([])

// 列显隐配置
const columns = ref([
  { key: 0, label: '方案名称', visible: true },
  { key: 1, label: '方案描述', visible: true },
  { key: 2, label: '系统名称', visible: true },
  { key: 3, label: '是否默认', visible: true },
  { key: 4, label: '用户类型', visible: true },
  { key: 5, label: '菜单集合', visible: true },
  { key: 6, label: '创建时间', visible: true },
  { key: 7, label: '创建人', visible: true },
  { key: 8, label: '操作', visible: true }
])

// 表单验证规则
const rules = reactive({
  schemeName: [
    { required: true, message: '请输入方案名称', trigger: 'blur' }
  ],
  systemName: [
    { required: true, message: '请输入系统名称', trigger: 'blur' }
  ],
  userType: [
    { required: true, message: '请选择用户类型', trigger: 'blur' }
  ],
  isDefault: [
    { required: true, message: '请选择是否默认', trigger: 'blur' }
  ],
})

// 获取用户类型标签
const getUserTypeLabel = (type) => {
  const map = {
    admin: '管理员',
    user: '普通用户',
    guest: '访客'
  }
  return map[type] || type
}

// 获取用户类型标签类型
const getUserTypeTagType = (type) => {
  const map = {
    admin: 'danger',
    user: 'primary',
    guest: 'info'
  }
  return map[type] || 'info'
}

// 计算时间范围
const computedTimeRange = () => {
  if (timeRange.value && timeRange.value.length === 2) {
    queryParams.startTime = timeRange.value[0]
    queryParams.endTime = timeRange.value[1]
  } else {
    queryParams.startTime = ''
    queryParams.endTime = ''
  }
}

// 获取菜单方案列表
const fetchMenuSchemeList = async () => {
  try {
    loading.value = true
    computedTimeRange()

    const res = await listMenuSchemes(queryParams)
    schemeList.value = res.rows || []
    total.value = res.total || 0
  } catch (error) {
    console.error('获取菜单方案列表失败:', error)
    ElMessage.error('获取菜单方案列表失败')
  } finally {
    loading.value = false
  }
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  fetchMenuSchemeList()
}

// 重置查询
const resetQuery = () => {
  queryParams.pageNum = 1
  timeRange.value = []
  queryParams.schemeName = ''
  queryParams.systemName = ''
  queryParams.isDefault = ''
  fetchMenuSchemeList()
}

// 分页大小变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  fetchMenuSchemeList()
}

// 当前页码变化
const handleCurrentChange = (page) => {
  queryParams.pageNum = page
  fetchMenuSchemeList()
}

// 表格选择变化
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 新增按钮
const handleAdd = () => {
  dialog.visible = true
  dialog.title = '新增菜单方案'
  dialog.isEdit = false
}

// 编辑按钮
const handleEdit = (row) => {
  dialog.visible = true
  dialog.title = '编辑菜单方案'
  dialog.isEdit = true
  form.value = row
}

// 查看详情
const handleDetail = async (row) => {
  try {
    const res = await getMenuSchemeDetail(row.schemeId)
    detailData.value = res.data || {}
    detailDialog.visible = true
  } catch (error) {
    console.error('获取菜单方案详情失败:', error)
    ElMessage.error('获取菜单方案详情失败')
  }
}

// 查看菜单
const handleViewMenus = async (row) => {
  const menus = await getMenuCollectionList({ id:row.schemeId });
  
  menuDialog.visible = true
  menuDialog.schemeName = row.schemeName
  try {
    menuList.value = menus.data;
  } catch (error) {
    console.error('解析菜单集合失败:', error)
    menuList.value = []
    ElMessage.error('菜单集合格式错误')
  }
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(`确认删除菜单方案 "${row.schemeName}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    return deleteMenuSchemes([row.schemeId])
  }).then(() => {
    ElMessage.success('删除成功')
    fetchMenuSchemeList()
  }).catch(() => { })
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  const names = selectedRows.value.map(item => item.schemeName).join(', ')
  ElMessageBox.confirm(`确认删除选中的 ${selectedRows.value.length} 条记录吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const ids = selectedRows.value.map(item => item.schemeId)
    return deleteMenuSchemes(ids)
  }).then(() => {
    ElMessage.success('删除成功')
    fetchMenuSchemeList()
  }).catch(() => { })
}

// 导出数据
const handleExport = async () => {
  try {
    computedTimeRange()
    loading.value = true

    const res = await exportMenuSchemes(queryParams)
    const blob = new Blob([res], { type: 'application/vnd.ms-excel' })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = '菜单方案列表.xlsx'
    link.click()
    window.URL.revokeObjectURL(url)

    ElMessage.success('导出成功')
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    loading.value = false
  }
}

// 重置表单
const resetForm = () => {
  form.value = {
    schemeId: undefined,
    schemeName: '',
    schemeDesc: '',
    systemName: '',
    menuCollection: '',
    userType: '',
    isDefault: 0
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await formRef.value.validate()

    if (dialog.isEdit) {
      await updateMenuScheme(form.value)
      ElMessage.success('更新成功')
    } else {
      await addMenuScheme(form.value)
      ElMessage.success('新增成功')
    }

    dialog.visible = false
    fetchMenuSchemeList()
  } catch (error) {
    console.error('保存失败:', error)
    if (error !== 'validate') {
      ElMessage.error('操作失败')
    }
  }
}

// 初始化加载数据
onMounted(() => {
  fetchMenuSchemeList()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.mt-2 {
  margin-top: 20px;
}

.flex-end {
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.form-tip {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
}

/* 表格样式 */
:deep(.el-table) {
  width: 100%;
}

:deep(.el-table__cell) {
  padding: 12px 0;
}

/* 详情页样式 */
:deep(.el-descriptions) {
  margin-top: 20px;
}

:deep(.el-descriptions-item__label) {
  width: 120px;
  font-weight: bold;
}
</style>